package com.laolu.icon.utils;

import com.laolu.icon.constants.DesktopProperty;
import com.laolu.icon.entity.IconInfo;
import com.sun.jna.platform.win32.WinDef.RECT;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.List;

public class MyRectUtils {
	
	public static @NotNull RECT copyRECT(@NotNull RECT data) {
		RECT rect = new RECT();
		rect.left = data.left;
		rect.top = data.top;
		rect.right = data.right;
		rect.bottom = data.bottom;
		return rect;
	}
	
	public static boolean equalsRECT(@NotNull RECT rect1, @NotNull RECT rect2) {
		return rect1.left == rect2.left
				&& rect1.top == rect2.top
				&& rect1.right == rect2.right
				&& rect1.bottom == rect2.bottom;
	}
	
	public static boolean equalsRECTByLeftAndTop(@NotNull RECT rect1, @NotNull RECT rect2) {
		return rect1.left == rect2.left && rect1.top == rect2.top;
	}
	
	/**
	 * 获取桌面空闲位置用以放置占位图标
	 * @param list
	 * 		当前最新桌面图标信息列表
	 * @return 空闲位置
	 */
	public static @Nullable RECT getEmptyPosition(@NotNull List<IconInfo> list) {
		byte[][] position = new byte[DesktopProperty.v_maxCount][DesktopProperty.h_maxCount];
		for (IconInfo iconInfo : list) {
			RECT rect = iconInfo.getRect();
			int left = rect.left;
			int top = rect.top;
			int row = (top - DesktopProperty.startTop) / DesktopProperty.v_spacing;
			int column = (left - DesktopProperty.startLeft) / DesktopProperty.h_spacing;
			
			position[row][column] = 1;
		}
		
		for (int i = 0; i < DesktopProperty.h_maxCount; i++) {
			for (int j = 0; j < DesktopProperty.v_maxCount; j++) {
				if (position[j][i] == 0) {
					RECT rect = new RECT();
					rect.left = DesktopProperty.startLeft + i * DesktopProperty.h_spacing;
					rect.top = DesktopProperty.startTop + j * DesktopProperty.v_spacing;
					return rect;
				}
			}
		}
		
		
		return null;
	}
	
	/**
	 * 验证图标位置是否被占用
	 * @param iconPosition
	 * 		要验证的图标位置
	 * @param list
	 * 		当前最新桌面图标信息列表
	 * @return -1.位置没有被占用  >=0.占用指定位置的图标下表索引
	 */
	public static int validateIconPosition(RECT iconPosition, @NotNull List<IconInfo> list) {
		for (int i = 0; i < list.size(); i++) {
			if (equalsRECTByLeftAndTop(iconPosition, list.get(i).getRect())) {
				return i;
			}
		}
		return -1;
	}
	
}
